# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from functools import wraps

from modelos import Professor
from flask import render_template, request, redirect, url_for, g, session, flash

from __init__ import app

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user_id is None:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route("/login")
def login():

    return render_template("form_login.html")

#processo de logout
@app.route("/logout")
def logout():

    session.pop("user_id", None)
    session.pop("user", None)

    return redirect(url_for("login"))


#Processo de login
@app.route("/login_process", methods=['GET', 'POST'])
def login_process():

    session.pop("user_id", None)
    session.pop("user", None)

    usuario = request.form["login"]
    senha = request.form["senha"]

    try:
        p = Professor.get(Professor.usuario == usuario, Professor.senha == senha)

        session.modified = True

        session["user_id"] = p.id
        g.user_id = p.id

        return redirect(url_for("index"))

    except:

        flash("Usuário e/ou senha inválidos.", category="erro")

        return redirect(url_for("login"))

#cadastrar um profesor
@app.route("/form_add_professor", methods=['GET', 'POST'])
def form_add_professor():

    session.pop("user_id", None)
    session.pop("user", None)

    if request.method == "POST":
        usuario = request.form.get("usuario", None)
        senha = request.form.get("senha", None)

        if not usuario or not senha:

            flash('Usuario ou senha em branco, preencha corretamente.', category="erro")

            return render_template("form_add_professor.html")

        Professor.create(usuario=usuario, senha=senha)

        flash('Professor cadastrado corretamente', category="ok")

        return redirect(url_for('login'))

    return render_template("form_add_professor.html")   